<template>
  <view class="my-page">
    <!-- 用户信息区域 -->
    <view class="user-info">
      <image class="avatar" :src="userInfo && userInfo.avatar ? userInfo.avatar : 'https://q2.itc.cn/q_70/images03/20250225/e8117dd40aae4db5a64461f1ea0d16fc.jpeg'"></image>
      <view class="user-details">
        <text class="username">{{ userInfo && userInfo.username ? userInfo.username : '未登录' }}</text>
        <text class="user-id">手机号: {{ userInfo && userInfo.phone ? userInfo.phone : '未登录' }}</text>
      </view>
    </view>
    
    <!-- 功能按钮区域 -->
    <view class="function-buttons">
      <navigator url="/pages/appointment/list" class="btn-item" hover-class="none" @click="navigateToPage('/pageMember/setting/reserved-order/reserved-order')">
        <image class="btn-icon" src="../../static/yuyue.png"></image>
        <text class="btn-text">我的预约</text>
      </navigator>
      <navigator url="/pages/medical-record/list" class="btn-item" hover-class="none" @click="navigateToPage('/pageMember/setting/record/record')">
        <image class="btn-icon" src="../../static/jiuzhenjilu.png"></image>
        <text class="btn-text">就诊记录</text>
      </navigator>
      <navigator url="/pages/prescription/list" class="btn-item" hover-class="none" @click="navigateToPage('/pageMember/setting/patient-list/patient-list')">
        <image class="btn-icon" src="../../static/chufang.png"></image>
        <text class="btn-text">患者列表</text>
      </navigator>
      <navigator url="/pages/health-card/list" class="btn-item" hover-class="none" @click="navigateToPage('/pages/index/components/healthFile')">
        <image class="btn-icon" src="../../static/dangan.png"></image>
        <text class="btn-text">健康档案</text>
      </navigator>
    </view>

    <!-- 设置选项区域 -->
    <view class="settings-list">
      <navigator url="/pages/setting/profile" class="setting-item" hover-class="none" @click="navigateToPage('/pageMember/setting/my-Information/my-Information')">
        <text class="setting-text">个人资料</text>
        <image class="arrow-icon" src="../../static/xiangyou.png"></image>
      </navigator>
      <navigator url="/pages/setting/notification" class="setting-item" hover-class="none">
        <text class="setting-text">通知设置</text>
        <image class="arrow-icon" src="../../static/xiangyou.png"></image>
      </navigator>
      <navigator url="/pages/setting/help" class="setting-item" hover-class="none" @click="navigateToPage('/pageMember/setting/help/help')">
        <text class="setting-text">帮助中心</text>
        <image class="arrow-icon" src="../../static/xiangyou.png"></image>
      </navigator>
      <navigator url="/pages/setting/about" class="setting-item" hover-class="none" @click="navigateToPage('/pageMember/setting/about/about')">
        <text class="setting-text">关于我们</text>
        <image class="arrow-icon" src="../../static/xiangyou.png"></image>
      </navigator>
    </view>

    <!-- 退出登录按钮 -->
    <button class="logout-btn" @click="logout" v-if="userInfo">退出登录</button>
    <button class="gologin-btn" @click="navigateToPage('/pages/login/login')" v-else>登录</button>
  </view>
</template>

<script>
export default {
  data() {
    return {
      userInfo: null // 初始化为null
    }
  },
  onShow() {
    const token = uni.getStorageSync('token');
    if (!token) {
      this.userInfo = null; // 未登录
      return;
    }

    // 先从本地存储获取用户信息
    const storedUserInfo = uni.getStorageSync('userInfo');
    if (storedUserInfo && Object.keys(storedUserInfo).length > 0) {
      // 如果本地有用户信息，先显示本地信息
      this.userInfo = storedUserInfo;
    }

    // 然后尝试从服务器刷新用户信息
    uni.request({
      url: 'http://localhost:3000/api/user/info',
      method: 'GET',
      header: {
        'Authorization': 'Bearer ' + token
      },
      success: (res) => {
        const { code, data, message } = res.data;
        if (code === 200) {
          if (data && Object.keys(data).length > 0) {
            this.userInfo = data;
            // 更新本地存储的用户信息
            uni.setStorageSync('userInfo', data);
          } else {
            console.error('服务器返回的用户信息为空');
          }
        } else {
          // 针对"用户不存在"错误进行特殊处理，不打印错误日志
          if (message && message.includes('用户不存在')) {
            // 如果没有本地缓存，才显示错误
            if (!storedUserInfo || Object.keys(storedUserInfo).length === 0) {
              uni.showToast({ title: '用户信息获取失败，请重新登录', icon: 'none' });
              setTimeout(() => {
                this.navigateToPage('/pages/login/login');
              }, 1500);
            }
          } else {
            // 其他类型的错误，记录日志
            // console.error('获取用户信息失败:', message);
            // 针对token失效的处理
            if (message && message.includes('token') || message && message.includes('expired')) {
              // token 失效，清除并跳转登录
              uni.removeStorageSync('token');
              uni.removeStorageSync('userInfo');
              this.userInfo = null;
              uni.showToast({ title: '登录已过期，请重新登录', icon: 'none' });
              setTimeout(() => {
                this.navigateToPage('/pages/login/login');
              }, 1500);
            } else {
              // 其他错误，继续使用本地缓存的用户信息
              if (!storedUserInfo || Object.keys(storedUserInfo).length === 0) {
                // 如果没有本地缓存，显示错误但不清除token
                uni.showToast({ title: message || '获取用户信息失败', icon: 'none' });
              }
            }
          }
        }
      },
      fail: (err) => {
        console.error('获取用户信息网络错误:', err);
        // 网络错误时，如果有本地缓存的用户信息，继续使用
        if (!storedUserInfo || Object.keys(storedUserInfo).length === 0) {
          // 如果没有本地缓存，显示网络错误
          uni.showToast({ title: '网络连接失败，无法获取用户信息', icon: 'none' });
        } else {
          // 如果有本地缓存，提示用户使用的是缓存数据
          uni.showToast({ title: '正在使用本地缓存数据', icon: 'none' });
        }
      }
    });
  },
  methods: {
    // 通用导航方法
    navigateToPage(path) {
    //获取token
    const token = uni.getStorageSync('token');
    if (!token) {
      uni.showToast({ title: '请先登录', icon: 'none' });
      setTimeout(() => {
        uni.reLaunch({
          url: '/pages/login/login'
        });
      }, 1500);
      return;
    }
      uni.navigateTo({
        url: path
      });
    },
    
    logout() {
      uni.showModal({
        title: '提示',
        content: '确定要退出登录吗？',
        success: (res) => {
          if (res.confirm) {
            uni.removeStorageSync('userInfo');
            uni.removeStorageSync('token'); // 清除 token
            uni.reLaunch({
              url: '/pages/login/login'
            });
          }
        }
      });
    }
  }
}
</script>

<style scoped>
/* 页面容器样式 */
.my-page {
  min-height: 100vh;
  background-color: #f5f5f5;
  padding-bottom: 30px;
}

/* 用户信息区域样式 */
.user-info {
  background-color: #1E88E5;
  padding: 40px 20px 20px;
  display: flex;
  align-items: center;
  color: white;
}

.avatar {
  width: 80px;
  height: 80px;
  border-radius: 50%;
  background-color: white;
  margin-right: 15px;
}

.user-details {
  flex: 1;
}

.username {
  font-size: 20px;
  font-weight: bold;
  margin-bottom: 5px;
  display: block;
}

.user-id {
  font-size: 14px;
  opacity: 0.9;
}

.edit-btn {
  font-size: 14px;
  border: 1px solid white;
  padding: 5px 10px;
  border-radius: 20px;
}

/* 功能按钮区域样式 */
.function-buttons {
  display: flex;
  flex-wrap: wrap;
  background-color: white;
  margin: 15px;
  border-radius: 10px;
  padding: 20px 0;
}

.btn-item {
  width: 25%;
  display: flex;
  flex-direction: column;
  align-items: center;
  text-decoration: none;
}

.btn-icon {
  width: 40px;
  height: 40px;
  margin-bottom: 8px;
}

.btn-text {
  color: #333;
  font-size: 14px;
}

/* 设置选项区域样式 */
.settings-list {
  background-color: white;
  margin: 0 15px 15px;
  border-radius: 10px;
}

.setting-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px 20px;
  border-bottom: 1px solid #eee;
  text-decoration: none;
}

.setting-item:last-child {
  border-bottom: none;
}

.setting-text {
  color: #333;
  font-size: 16px;
}

.arrow-icon {
  width: 16px;
  height: 16px;
  opacity: 0.5;
}

/* 未登录状态样式 */
.login-prompt {
  text-align: center;
  padding: 50px 20px;
}

.login-bg {
  width: 120px;
  height: 120px;
  margin-bottom: 20px;
  opacity: 0.7;
}

.login-text {
  display: block;
  font-size: 16px;
  color: #666;
  margin-bottom: 30px;
}

.login-btn {
  background-color: #1E88E5;
  color: white;
  width: 80%;
  height: 45px;
  border-radius: 25px;
  font-size: 16px;
}
</style>